# coding=utf8

import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr, formatdate

from zUtils import config

email_config = config['Email']


def _format_addr(s):
    # return Alias_name <xxxx@example.com>
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


def render_mail(to_addrs, subject, html):
    # 指定subtype为alternative，同时支持html和plain格式
    msg = MIMEMultipart('alternative')
    # msg.attach(MIMEText(plain, 'plain', 'utf-8'))  # 纯文本
    msg.attach(MIMEText(html, 'html', 'utf-8'))  # HTML
    ''' 添加附件：即关联一个MIMEBase，图片为本地读取
    with open('./hope.jpg', 'rb') as f:
        # 设置附件中的MIME和文件名
        mime = MIMEBase('image', 'jpeg', filename='hope.jpg')
        # 加上必要的头信息
        mime.add_header('Content-Disposition', 'attachment', filename='hope.jpg')
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来
        mime.set_payload(f.read())
        # 用Base64编码
        encoders.encode_base64(mime)
        # 添加到MIMEMultipart
        msg.attach(mime)
    '''
    msg['From'] = _format_addr('%s<%s>' % (email_config['Alias'], email_config['Username']))
    msg['To'] = '%s' % ','.join([_format_addr('<%s>' % to_addr) for to_addr in to_addrs])
    msg['Subject'] = Header(subject, 'utf-8').encode()
    msg['Date'] = formatdate()
    return msg.as_string()


def send_email(to_addrs, msg):
    try:
        with smtplib.SMTP(email_config['SMTPServer'], email_config['Port']) as server:  # SMTP协议默认端口是25
            server.set_debuglevel(1)
            server.starttls()
            server.login(email_config['Username'], email_config['Password'])
            # 如果有多个邮件地址，用,分隔即可
            server.sendmail(email_config['Username'], to_addrs, msg)
    except Exception as e:
        print(e)
        return False
    return True
